// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import "SteelmillAppDelegate.h"
#import "cocos2d.h"
#import "PuzzleScene.h"
#import "PuzzleCommon.h"

#if USE_OPENFEINT
#import "OpenFeint.h"
#endif  // #if USE_OPENFEINT

@implementation SteelmillAppDelegate

@synthesize window;

- (void) applicationDidFinishLaunching:(UIApplication*)application
{
	// Init the window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	
	if(![CCDirector setDirectorType:CCDirectorTypeDisplayLink]) {
		assert(false);
	}
	
	[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
	
#if AUTOROTATEANIMATION
	[[CCDirector sharedDirector] setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
	[[CCDirector sharedDirector] setDeviceOrientation:kCCDeviceOrientationLandscapeRight];
#endif
	[[CCDirector sharedDirector] setAnimationInterval:1.0/60];
	[[CCDirector sharedDirector] setDisplayFPS:SHOW_FPS];

	EAGLView *glView = [EAGLView viewWithFrame:[window bounds]];
	[glView setUserInteractionEnabled:YES];	
	[glView setMultipleTouchEnabled:YES];

	SteelmillViewController* viewController =
		[[SteelmillViewController alloc] initWithNibName:nil bundle:nil];
	viewController.wantsFullScreenLayout = YES;
	[viewController setView:glView];
		
	[[CCDirector sharedDirector] setOpenGLView:glView];
	[window addSubview:viewController.view];
	
	[window makeKeyAndVisible];		
		
	srand(time(NULL));
	
	SceneManager* scene = [SceneManager sceneManager];
	if(SKIP_MENUS) {
		[scene changeLayout:(SKIP_TWOPLAYER ? (SKIP_REVERSED ? TWOPLAYERSREVERSED : TWOPLAYERS) : SINGLEPLAYER)];
		[scene changeState:PLAYING];
	} else {
		[scene changeState:MAINMENU];
	}
	[[CCDirector sharedDirector] runWithScene:scene];

#if USE_OPENFEINT
	NSDictionary* openfeintsettings = [NSDictionary dictionaryWithObjectsAndKeys:
		[NSNumber numberWithInt:scene->bufferedLandscapeOrientation_], OpenFeintSettingDashboardOrientation,
		@"Steel Mill", OpenFeintSettingShortDisplayName, 
		[NSNumber numberWithBool:NO], OpenFeintSettingEnablePushNotifications,
//		[NSNumber numberWithBool:NO], OpenFeintSettingDisableChat,
		nil
	];

//	OpenFeintDelegate* ofDelegate = [OpenFeintDelegate new];
	OFDelegatesContainer* delegates = [OFDelegatesContainer containerWithOpenFeintDelegate:nil/*ofDelegate*/];

    [OpenFeint initializeWithProductKey:@""
                              andSecret:@""
                         andDisplayName:@"Steel Mill"
                            andSettings:openfeintsettings    // see OpenFeintSettings.h
                           andDelegates:delegates];          // see OFDelegatesContainer.h
                           
    // You probably want to invoke this from a button instead of directly here.
    [OpenFeint launchDashboard];
#endif  // #if USE_OPENFEINT
}


- (void)applicationWillResignActive:(UIApplication *)application {
	if(scene->ispaused_) { [scene endPause]; }
	[[CCDirector sharedDirector] pause];
#if USE_OPENFEINT
	[OpenFeint applicationWillResignActive];
#endif  // #if USE_OPENFEINT
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	[[CCDirector sharedDirector] resume];
#if USE_OPENFEINT
	[OpenFeint applicationDidBecomeActive];
#endif  // #if USE_OPENFEINT
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
	// Log the memory warning so that we can clear out some space the next time we
	// return to main menu.
	scene->memorywarning_ = true;
}

- (void)applicationWillTerminate:(UIApplication *)application {
	[[CCDirector sharedDirector] end];
#if USE_OPENFEINT
	[OpenFeint shutdown];
#endif  // #if USE_OPENFEINT
}

- (void)applicationDidEnterBackground:(UIApplication *)application 
{
	if(scene->ispaused_) { [scene endPause]; }

	[[CCDirector sharedDirector] stopAnimation];
	[[CCDirector sharedDirector] pause];

#if USE_OPENFEINT
	[OpenFeint applicationDidEnterBackground];
#endif  // #if USE_OPENFEINT
}

- (void)applicationWillEnterForeground:(UIApplication *)application 
{
	[[CCDirector sharedDirector] resume];
	[[CCDirector sharedDirector] startAnimation];

#if USE_OPENFEINT
	[OpenFeint applicationWillEnterForeground];
#endif  // #if USE_OPENFEINT
}

- (void)applicationSignificantTimeChange:(UIApplication *)application {
	[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}

- (void)dealloc {
	[[CCDirector sharedDirector] release];
	[window release];
	[super dealloc];
}

@end


@implementation SteelmillViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Don't let the UIViewController autorotate since we're doing it ourselves.
	return NO;
}


// Use this notification trick to get around the fact that shouldAutorotate will never get called for Portrait.
-(void) viewWillAppear: (BOOL) animated{
	[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(receivedRotate:) name: UIDeviceOrientationDidChangeNotification object: nil];
}

-(void) viewWillDisappear: (BOOL) animated{
	[[NSNotificationCenter defaultCenter] removeObserver: self];
	[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
}

-(void) receivedRotate: (NSNotification*) notification
{
	UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation) [[UIDevice currentDevice] orientation];
	ccDeviceOrientation deviceOrientation;
	switch(interfaceOrientation) {
		case UIInterfaceOrientationPortrait:
			deviceOrientation = kCCDeviceOrientationPortrait;
			break;
		case UIInterfaceOrientationPortraitUpsideDown:
			deviceOrientation = kCCDeviceOrientationPortraitUpsideDown;
			break;
		case UIInterfaceOrientationLandscapeLeft:
			// cocos2d inverts landscapeLeft and landscapeRight
			deviceOrientation = kCCDeviceOrientationLandscapeRight;
			break;
		case UIInterfaceOrientationLandscapeRight:
			deviceOrientation = kCCDeviceOrientationLandscapeLeft;
			break;
		default:
			return;
	}
	[scene receiveUserOrientation:deviceOrientation];
}

@end
